<template>
    <el-container style="min-height: 100vh; border: 1px solid #eee">
      <el-aside :width="sideWidth+'px'" style="background-color: rgb(238, 241, 246); box-shadow: 2px 0 6px rgb(0 21 41 /35%)">
        <el-menu :default-openeds="['1', '3']" style="height: 100%;overflow-x: hidden"
                 background-color="rgb(48,65,86)"
                 text-color="#fff"
                 active-text-color="#ffd04b"
                 :collapse-transition="false"
                 :collapse="isCollapse">

          <div style="height: 60px; line-height: 60px; text-align: center">
            <img src="../assets/logo.png" alt="" style="width: 20px; position: relative; top:5px; margin-right: 5px">
            <b style="color: white" v-show="logoTextShow">管理端系统</b>
          </div>

          <el-submenu index="1">
            <template slot="title">
              <i class="el-icon-user-solid"></i>
              <span slot="title">用户</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="1-1">选项1</el-menu-item>
              <el-menu-item index="1-2">选项2</el-menu-item>
            </el-menu-item-group>
            </el-submenu>

          <el-submenu index="2">
            <template slot="title">
              <i class="el-icon-star-on"></i>
              <span slot="title">动态</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="2-1">选项1</el-menu-item>
              <el-menu-item index="2-2">选项2</el-menu-item>
            </el-menu-item-group>
            </el-submenu>

          <el-submenu index="3">
            <template slot="title">
              <i class="el-icon-s-promotion"></i>
              <span slot="title">资讯</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="3-1">选项1</el-menu-item>
              <el-menu-item index="3-2">选项2</el-menu-item>
            </el-menu-item-group>
            </el-submenu>

        </el-menu>
      </el-aside>

      <el-container>
<!--        导航栏-->
        <el-header style="font-size: 12px; border-bottom: 1px solid #ccc; line-height: 60px;display: flex">
          <div style="flex: 1; font-size: 18px">
            <span :class="collapseBtnClass" style="cursor: pointer" @click="collapse"></span>
          </div>
          <el-dropdown style="width: 70px;cursor:pointer;">
            <span>Kassel</span><i class="el-icon-arrow-down" style="margin-left: 5px"></i>

            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>个人信息</el-dropdown-item>
              <el-dropdown-item>退出</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>

        <el-main>
          <div style="margin-bottom: 30px">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
            </el-breadcrumb>
          </div>

<!--          搜索-->
          <div style="padding: 10px 0">
            <el-select v-model="selectedOption" placeholder="请选择搜索项" style="width: 120px;">
              <el-option
                  v-for="(item, index) in options"
                  :key="index"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
            <el-input style="width: 200px" suffix-icon="el-icon-search" placeholder="请输入搜索项的值" v-model="value" @change="change()" @keyup.native.enter="search"></el-input>
            <el-button class="ml-5" type="primary" @click="search">搜索</el-button>
            <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
          </div>

          <div style="margin: 10px 0; display: flex; align-items: center;">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item style="margin-right: 15px">共{{DataNum}}条数据</el-breadcrumb-item>
            </el-breadcrumb>
            <el-button type="primary" @click="addUser">新增<i class="el-icon-circle-plus-outline"></i> </el-button>
            <el-button type="danger" @click="deleteSelectedRows">批量删除<i class="el-icon-remove-outline"></i> </el-button>
            <el-button type="primary" @click="importData">导入<i class="el-icon-bottom"></i> </el-button>
            <el-button type="primary" @click="exportData">导出<i class="el-icon-top"></i> </el-button>
          </div>

<!--          表格-->
          <el-table :data="tableData" border stripe :header-cell-class-name="headerBg" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="user_pic" label="头像" width="90">
              <template slot-scope="scope">
                <img :src="scope.row.user_pic" alt="头像" style="width: 60px; height: 60px; object-fit: cover;">
              </template>
            </el-table-column>
            <el-table-column prop="id" label="ID" width="90">
            </el-table-column>
            <el-table-column prop="username" label="用户" width="150">
            </el-table-column>
            <el-table-column prop="sex" label="性别" width="90">
            </el-table-column>
            <el-table-column prop="password" label="密码" width="150" :formatter="formatPassword" >
            </el-table-column>
            <el-table-column prop="nickname" label="昵称" width="150">
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="150">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="info" @click="viewData(scope.row)">查看<i class="el-icon-edit"></i> </el-button>
                <el-button type="success" @click="editData(scope.row)">编辑<i class="el-icon-edit"></i> </el-button>
                <el-button type="danger" @click="deleteData(scope.row)">删除<i class="el-icon-remove-outline"></i></el-button>
              </template>
            </el-table-column>
          </el-table>

<!--          分页-->
          <div style="padding: 10px 0">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[10, 5, 15, 20,DataNum]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total=DataNum>
            </el-pagination>
          </div>


          <el-dialog title="新增用户" :visible.sync="dialogFormVisible" width="35%">
            <el-form label-width="80px" size="small">
              <el-form-item label="用户">
                <el-input v-model="form.username" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-input v-model="form.sex" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="form.password" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="form.nickname" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="form.email" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUserToSQL">确 定</el-button>
            </div>
          </el-dialog>

          <el-dialog title="编辑用户" :visible.sync="editFormVisible" width="35%">
            <el-form label-width="80px" size="small">
              <el-form-item label="ID">
                <el-input v-model="editForm.id" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="用户">
                <el-input v-model="editForm.username" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-input v-model="editForm.sex" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="editForm.password" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="editForm.nickname" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="editForm.email" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="editFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUserToSQL">确 定</el-button>
            </div>
          </el-dialog>

          <el-dialog title="用户详细信息" :visible.sync="detailFormVisible" width="35%">
            <el-form label-width="80px" size="small">
              <el-form-item label="ID">
                <el-input v-model="detailForm.id" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="用户">
                <el-input v-model="detailForm.username" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-input v-model="detailForm.sex" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="detailForm.password" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="detailForm.nickname" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="detailForm.email" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-input v-model="detailForm.createTime" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
              <el-form-item label="最新更新时间">
                <el-input v-model="detailForm.updateTime" autocomplete="off" :readonly="true"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="editFormVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUserToSQL">确 定</el-button>
            </div>
          </el-dialog>


        </el-main>
      </el-container>
    </el-container>

</template>


<script>
export default {
  name: 'HomeView',

  data() {
    return {
      baseUrl: 'http://localhost:9090/api',
      user_pic:'',
      selectedIds: [],
      tableData: [],
      value: '',
      pageSize: 10,
      pageNum: 1,
      DataNum: 0,
      isCollapse: false,//导航栏是否折叠情况
      sideWidth: 200,
      collapseBtnClass: 'el-icon-s-fold',
      isCollapsed: false,
      logoTextShow: true,
      dialogFormVisible: false,//dialog是否出现
      editFormVisible: false,
      detailFormVisible: false,
      form: {},//用户表单
      editForm:{},
      detailForm:{},
      headerBg: 'headerBg',
      selectedOption: '',
      options: [
        {label: 'ID', value: 'id'},
        {label: '用户', value: 'username'},
        {label: '性别', value: 'sex'},
        {label: '昵称', value: 'nickname'},
        {label: '邮箱', value: 'email'}
      ]
    }
  },

  created() {
    this.load()
  },

  methods: {
    //查看详细信息
    formatPassword() {
      // 将密码内容替换为星号
      return '*********'
    },
    viewData(row) {
      fetch(this.baseUrl+"/details?userId=" + row.id)
          .then(res => res.json())
          .then(res => {
            // 在异步请求返回结果后执行赋值操作
            this.detailForm = row; // 先将 row 赋值给 detailForm
            this.detailForm.createTime = res[0]; // 然后设置 createTime
            this.detailForm.updateTime = res[1]; // 最后设置 updateTime
            this.detailFormVisible = true;
          });
    },
    //批量删除
    handleSelectionChange(selection) {
      // 获取选中项的 ID
      this.selectedIds = selection.map(item => item.id);
    },
    deleteSelectedRows(){
      const formData = {
        selectedId: this.selectedIds
      };
      this.$confirm('是否确定批量删除选中的用户?', '批量删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post(this.baseUrl+'/deletes', formData)
            .then(response => {
              this.$message({
                type: 'success',
                message: '用户已成功删除'
              });
              this.load()
            })
            .catch(error => {
              console.error('Error:', error);
            });
      }).catch(() => {
        // 如果用户点击了取消按钮
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //编辑
    editData(row){
      this.editForm=row
      this.editFormVisible=true
    },
    editUserToSQL(){
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1; // 加1得到实际月份
      const day = currentDate.getDate(); // 获取月份中的某一天
      const hours = currentDate.getHours();
      const minutes = currentDate.getMinutes();
      const seconds = currentDate.getSeconds();

      const currentTime = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
      const formData = {
        id: this.editForm.id,
        username: this.editForm.username,
        sex: this.editForm.sex,
        password: this.editForm.password,
        nickname: this.editForm.nickname,
        email: this.editForm.email,
        updateTime:currentTime
      };
      // 发送请求
      this.$confirm('是否确定修改该用户数据?', '编辑用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post(this.baseUrl+'/edit', formData)
            .then(res => {
              this.editFormVisible = false
              this.$message({
                type: 'success',
                message: '用户信息已成功修改'
              });
              this.load()
            })
            .catch(error => {
              console.error('Error:', error);
            });
      }).catch(() => {
        // 如果用户点击了取消按钮
        this.$message({
          type: 'info',
          message: '已取消编辑'
        });
      });
    },
    //删除
    deleteData(row){
      const formData = {
        id: row.id
      };
      this.$confirm('是否确定删除该用户?', '删除用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post(this.baseUrl+'/delete', formData)
            .then(response => {
              this.$message({
                type: 'success',
                message: '用户已成功删除'
              });
              this.load()
            })
            .catch(error => {
              console.error('Error:', error);
            });
      }).catch(() => {
        // 如果用户点击了取消按钮
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //查找
    search(){
      // 构造请求参数对象
      const requestData = {
        optionSelect: this.selectedOption,
        optionValue: this.value,
        pageNumber: this.pageNum,
        pageSize: this.pageSize
      };

      // 发送 POST 请求
      axios.post(this.baseUrl+'/search', requestData)
          .then(response => {
            // 请求成功处理
            this.tableData = response.data.data;
            this.DataNum = response.data.total;
          })
          .catch(error => {
            // 请求失败处理
            console.error('请求失败:', error);
          });
    },
    //新增
    addUser(){
      this.dialogFormVisible = true
      this.form = {}
    },
    //让输入框可以输入数据
    change(){//标签嵌套太深，会导致无法获取到DOM->el-input无法输入内容,需要$forceUpdate()强制更新
      this.$forceUpdate()
    },
    //重置
    reset(){
      this.selectedOption = ''
      this.value = ''
      this.load()
    },
    //改变页尺寸
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.load()
    },
    //改变每页数量
    handleCurrentChange(pageNum){
      this.pageNum = pageNum
      this.load()
    },
    //从后端获取分页查询数据
    load(){
      fetch(this.baseUrl+"/initialize?pageNumber=" + this.pageNum + "&pageSize=" + this.pageSize).then(res => res.json()).then(res => {
        this.tableData = res.data
        this.DataNum = res.total
      })
    },
    //新增用户
    addUserToSQL(){
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1; // 加1得到实际月份
      const day = currentDate.getDate(); // 获取月份中的某一天
      const hours = currentDate.getHours();
      const minutes = currentDate.getMinutes();
      const seconds = currentDate.getSeconds();

      const currentTime = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${seconds < 10 ? '0' + seconds : seconds}`;


      const formData = {
        username: this.form.username,
        sex: this.form.sex,
        password: this.form.password,
        nickname: this.form.nickname,
        email: this.form.email,
        createTime: currentTime,
        updateTime: currentTime
      };

      this.$confirm('是否确定新增该用户?', '新增用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post(this.baseUrl+'/add', formData)
            .then(response => {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: '用户信息已成功入库'
              });
              this.load()
            })
            .catch(error => {
              console.error('Error:', error);
            });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消新增'
        });
      });
    },
    //导入数据
    importData(){
      // 创建一个隐藏的文件选择框
      let fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = '.csv, text/plain'; // 限制选择的文件类型为CSV和文本文件
      fileInput.style.display = 'none';
      document.body.appendChild(fileInput);

      // 监听文件选择事件
      fileInput.addEventListener('change', () => {
        let formData = new FormData();
        formData.append('file', fileInput.files[0]);

        this.$confirm('是否确定导入该文件?', '导入数据', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 如果用户点击了确定按钮
          axios.post(this.baseUrl+'/upload', formData)
              .then(response => {
                this.$message({
                  type: 'success',
                  message: '数据导入成功'
                });
                this.load()
              })
              .catch(error => {
                console.error(error);
                this.$message({
                  type: 'error',
                  message: '数据导入失败'
                });
              })
              .finally(() => {
                // 选择文件后移除文件选择框
                document.body.removeChild(fileInput);
              });
        }).catch(() => {
          // 如果用户点击了取消按钮
          this.$message({
            type: 'info',
            message: '已取消导入'
          });
        });
      });
      // 模拟点击文件选择框
      fileInput.click();
    },
    //导出数据
    exportData(){//导出数据为CSV格式
      this.$confirm('是否确定导出该页数据?', '导出数据', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 如果用户点击了确定按钮
        // 将数据转换成 CSV 格式
        const csvContent = this.convertToCSV(this.tableData);

        // 创建一个 Blob 对象
        const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});

        // 创建一个下载链接
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', 'data.csv');

        // 触发点击下载链接
        link.click();

        // 释放 Blob 对象
        URL.revokeObjectURL(url);
        this.$message({
          type: 'success',
          message: '数据导出成功'
        });
      }).catch(() => {
        // 如果用户点击了取消按钮
        this.$message({
          type: 'info',
          message: '已取消导出'
        });
      });
    },
    convertToCSV(data) {
      const header = Object.keys(data[0]).join(',');
      const content = data.map(obj => Object.values(obj).join(',')).join('\n');
      return `${header}\n${content}`;
    },
    //导航栏的收缩与打开
    collapse(){//收缩
      this.isCollapse = !this.isCollapse
      if (this.isCollapse) {//收缩
        this.sideWidth = 64
        this.collapseBtnClass = 'el-icon-s-unfold'
        this.logoTextShow = false
      } else {//展开
        this.sideWidth = 200
        this.collapseBtnClass = 'el-icon-s-fold'
        this.logoTextShow = true
      }
    }
  }
}
</script>

<style>
.headerBg{
  background-color: lightblue!important;
}
</style>
